package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.BaseConfigBean
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.RepairModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_repair.*
import kotlinx.android.synthetic.main.activity_title.*

class RepairActivity : BaseActivity<RepairModel>(), View.OnClickListener {

    private var codePop: PopWindowsUtils.GeneralPop? = null
    var list: ArrayList<String> = ArrayList()
    var repairType: String = ""
    var priority: String = "1"
    var groupName: String = "PE"
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@RepairActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }
    override fun initData() {

//        queryEqpData(etEqpId)

        viewModel.defUI.callObserve.observe(this@RepairActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        list.clear()
                        val baseConfigBean = it.item as BaseConfigBean
                        for (item in baseConfigBean.mItemList) {
                            list.add(item.mItemValue)
                        }
                    }
                    2 -> {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("报修提交成功", true)
                        intent.setClass(this, HomeActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        tvBaseSubmit.visibility = View.GONE
        tvTitle.text = "报修"
        tvUserName.text = Constant.UserName
        rbRepairType0.setOnClickListener(this)
        rbRepairType1.setOnClickListener(this)
        rbRepairType2.setOnClickListener(this)
        rbRepairType3.setOnClickListener(this)
        rbPriority0.setOnClickListener(this)
        rbPriority1.setOnClickListener(this)
        rbPE.setOnClickListener(this)
        rbME.setOnClickListener(this)
//        rbPriority2.setOnClickListener(this)
        FreeApi_ActivityManager.getActivityManager().addActivity(this)
        val instance = MyApp.instance
        instance!!.handler = handler
        viewModel.defaultGetBaseConfig()

        flPositionList.setOnClickListener {
            if (codePop == null) {
                codePop = PopWindowsUtils.getOneChoosePop(this, flType.width, list,
                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            tvType.text = string
                        }
                    }
                )
            }

            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                codePop?.showAsDropDown(flType, 0, 0)
            }
        }

        btnRepair.setOnClickListener {
            if (Constant.isFastClick()) {
                if (etEqpId.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描设备ID", false)
                    return@setOnClickListener
                }

                if (repairType == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请选择报修类型", false)
                    return@setOnClickListener
                }

                if (repairType == "维修" && tvType.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请选择维修子项", false)
                    return@setOnClickListener
                }

                if (priority == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请选择优先级", false)
                    return@setOnClickListener
                }

                val map = JsonObject()
                map.addProperty("UserName", Constant.UserName)
                map.addProperty("EquipmentName", etEqpId.text.toString())
                map.addProperty("LotNo", "")
                map.addProperty("RepairsType", repairType)
                map.addProperty(
                    "MaintenanceItem",
                    if (repairType == "0") tvType.text.toString() else ""
                )
                map.addProperty("Priority", priority)
                map.addProperty("GroupName", groupName)
                map.addProperty("Comment", etComment.text.toString())
                viewModel.defaultRepair(map)
            }
        }
    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            viewModel.defaultEqpInfo(s!!)
        }

    }

    override fun layoutId(): Int {
        return R.layout.activity_repair
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.rbRepairType0 -> {
                repairType = "0"
                lineMaintenanceItem.visibility = View.VISIBLE
            }
            R.id.rbRepairType1 -> {
                repairType = "1"
                lineMaintenanceItem.visibility = View.VISIBLE
            }
            R.id.rbRepairType2 -> {
                repairType = "2"
                lineMaintenanceItem.visibility = View.GONE
            }
            R.id.rbRepairType3 -> {
                repairType = "3"
                lineMaintenanceItem.visibility = View.GONE
            }
            R.id.rbPriority0 -> {
                priority = "0"
            }
            R.id.rbPriority1 -> {
                priority = "1"
            }
            R.id.rbPE ->{
                groupName = "PE"
            }
            R.id.rbME ->{
                groupName = "ME"
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                108 -> {
                    finish()
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 520) {
            try {
                val view = window.decorView.findFocus() as EditText
                when (view) {
                    etEqpId ->{
                        etEqpId.setText("")
                    }
                }
            }catch (e: Exception){
                println(e.message)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}